#include "./../inc/draw.h"

int *getBMP_IMG(char *path, int width, int height)
{
    FILE *fp = fopen(path, "rb");
    if (fp == NULL)
    {
        // perror("BMP_fopen");
        return NULL;
    }
    // printf("open bmp success\n");

    fseek(fp, 54, SEEK_SET);

    char buf_bmp[height][width * 3];

    memset(buf_bmp, 0, height * width * 3);

    int padding = (4 - (width * 3) % 4) % 4; // 计算每行填充字节数
    
    // 逐行读取 bmp图片每一行的字节数必须是4的倍数
    for (int i = 0; i < height; i++)
    {
        fread(buf_bmp[i], width * 3, 1, fp);
        if (padding > 0)
        {
            fseek(fp, padding, SEEK_CUR); // 跳过填充字节
        }
    }
    fclose(fp);

    int *buf = malloc(height * width * sizeof(int));

    // 处理像素数据，BMP是从下到上存储的
    for (int i = 0; i < height; i++)
    {
        int cow = height - i - 1; // 翻转Y坐标
        for (int j = 0; j < width; j++)
        {
            // 注意：BMP存储顺序是BGR
            int b = buf_bmp[i][j * 3];
            int g = buf_bmp[i][j * 3 + 1];
            int r = buf_bmp[i][j * 3 + 2];

            // 组合成32位ARGB格式（Alpha=0）
            buf[cow * width + j] = (0x00 << 24) | (r << 16) | (g << 8) | b;
        }
    }

    return buf;
}
